<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Psy\Exception\ErrorException;

class CartController extends Controller
{
    public function index()
    {

//        初始化头
        $res = DB::table('businesses')
            ->select('business_address', 'username', 'send_costs', 'start_send_costs','id')
            ->where('id', '=', $_GET['business_id'])->first();
        return view('home.cart.checkout', ['data' => $res]);
    }

    /**
     * 初始化购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shopajax(Request $request)
    {

        $session = $request->session()->get('details');
        // 得到商品信息
        $data = [];
//        foreach ($session as $k => $v) {
            $res = DB::table('goods as g')
                ->select('d.num', 'g.proname', 'g.price', 'd.id')
                ->join('details as d', 'g.id', '=', 'd.goods_id')
                ->get();

//            array_push($data, $res);
//            dd($res);
//        }
//        dd($data);
        return response()->json($res);
    }

    public function shopajax_as(Request $request)
    {

        $data = $request->all();


        if ($data['num'] == 0) {
            DB::table('details')
                ->where('id', '=', $data['detail_id'])
                ->delete();

            $request->session()->forget('details');
            return response()->json(false);
        }

        DB::table('details')
            ->where('id', '=', $data['detail_id'])
            ->update(['num' => $data['num']]);

        $res = DB::table('goods as g')
            ->select('d.num', 'g.proname', 'g.price', 'd.id')
            ->join('details as d', 'g.id', '=', 'd.goods_id')
            ->first();

        return response()->json($res);
    }



    /**
     * 用户登录状态判断
     * @return \Illuminate\Http\JsonResponse
     */
    public function islogin() {

        return response()->json(session()->all()['master']->email);
    }

    public function logout() {
        session()->forget('master');
        return redirect('login');
    }
}
